import BlockButton from '@/components/BlockButton';
import TabHeader from '@/components/TabHeader';
import TextButton from '@/components/TextButton';
import { AppContext } from '@/store/index.context';
import { compact, times, uniq } from 'lodash';
import React, { useCallback, useContext, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { StartOneContext } from './index.context';
import PersonSelect from './PersonSelect';
import classes from './index.module.css';

export default function StartOne() {
  const { gameStore, personStore, messageStore } = useContext(AppContext);
  const { getPositionPersonIds, setStartTime, isGameStart, clearGame } =
    gameStore;
  const { getPersonsByIds } = personStore;
  const navigate = useNavigate();
  const [showPersonSelect, setShowPersonSelect] = useState(false);
  const [position, setPosition] = useState('');

  const positionPersons = useMemo(
    () => getPersonsByIds(getPositionPersonIds()),
    [getPositionPersonIds, getPersonsByIds],
  );

  const handleChoosePerson = useCallback(function (index: number) {
    const position = ['eastPerson', 'southPerson', 'westPerson', 'northPerson'][
      index
    ];
    setPosition(position);
    setShowPersonSelect(true);
  }, []);

  /** 开始一局新的游戏 */
  const handleStartGame = useCallback(() => {
    if (compact(positionPersons).length < 4) {
      messageStore.warning('请选择参数人员');
      return;
    }
    if (uniq(positionPersons).length < 4) {
      messageStore.warning('参赛人员不能重复');
      return;
    }
    setStartTime();
    navigate('/game');
  }, [navigate, messageStore, positionPersons, setStartTime]);

  /** 继续一局游戏 */
  const handleConsumeGame = useCallback(() => {
    navigate('/game');
  }, [navigate]);

  const handleGiveUp = useCallback(() => {
    messageStore.confirm('确定要放弃此局吗?', () => {
      clearGame();
    });
  }, [clearGame, messageStore]);

  return (
    <StartOneContext.Provider value={{ setShowPersonSelect, position }}>
      <TabHeader title={isGameStart ? '继续比赛' : '开始比赛'} />
      <div className={classes.StartOne}>
        {isGameStart ? <div>比赛已开始：</div> : <div>选择参赛人员：</div>}
        <div className={classes.Persons}>
          {times(4, index => (
            <div className={classes.OnePerson} key={index}>
              {['东', '南', '西', '北'][index]}：{positionPersons[index]?.name}
              {!isGameStart && (
                <TextButton onClick={() => handleChoosePerson(index)}>
                  选择
                </TextButton>
              )}
            </div>
          ))}
        </div>
        {showPersonSelect && <PersonSelect />}
        <div className={classes.Footer}>
          {isGameStart ? (
            <>
              <BlockButton onClick={handleGiveUp} text="放弃牌局" />
              <BlockButton
                onClick={handleConsumeGame}
                type="primary"
                text="继续牌局"
              />
            </>
          ) : (
            <BlockButton
              onClick={handleStartGame}
              type="primary"
              text="开始牌局"
            />
          )}
        </div>
      </div>
    </StartOneContext.Provider>
  );
}
